package com.rzico.sbl.ui.order

import android.os.Bundle
import android.os.PersistableBundle
import android.os.SystemClock
import android.view.View
import android.view.animation.BounceInterpolator
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.amap.api.maps.AMap
import com.amap.api.maps.AMap.InfoWindowAdapter
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CustomMapStyleOptions
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.setCameraChangeListener
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityOrderShipMapBinding
import com.rzico.sbl.model.MasterData
import com.rzico.sbl.model.OrderMapData
import com.rzico.sbl.viewmodel.OrderViewModel
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionElse
import com.xinnuo.common.extend.contact
import com.xinnuo.common.extend.find
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getByteFromAssets
import com.xinnuo.common.extend.inflate
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeByFinally
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class OrderShipMapActivity : BaseActivity(R.layout.activity_order_ship_map), InfoWindowAdapter {

    private val mBinding by lazy { ActivityOrderShipMapBinding.bind(getRootView()) }

    override fun getViewModel() = get<OrderViewModel>()

    // 店铺列表
    private val mShopList = arrayListOf<MasterData>()

    // 订单列表
    private val mShipList = arrayListOf<OrderMapData>()

    private var mSendMarker: Marker? = null

    override fun initData() {
        initTitle(title = "待发货订单")

        initAmap()
    }

    private fun initAmap() {
        mBinding.orderMap.map.apply {
            uiSettings.apply {
                isZoomControlsEnabled = false     //缩放按钮，默认打开
                isCompassEnabled = false          //指南针，默认不显示
                isMyLocationButtonEnabled = false //定位按钮
                isScaleControlsEnabled = true     //比例尺
                isScrollGesturesEnabled = true    //滑动手势
                isZoomGesturesEnabled = true      //缩放手势
                isRotateGesturesEnabled = true    //旋转手势
                isTiltGesturesEnabled = true      //倾斜手势
                setLogoBottomMargin(-100)         //隐藏logo
            }

            mapType = AMap.MAP_TYPE_NAVI   //导航地图模式
            isTrafficEnabled = true        //实时交通状况
            showBuildings(true)            //显示3D楼块
            showMapText(true)              //显示底图文字
            showIndoorMap(true)            //设置是否显示室内地图
            isMyLocationEnabled = false    //是否触发定位并显示定位层

            // 自定义地图
            setCustomMapStyle(
                CustomMapStyleOptions().apply {
                    isEnable = true
                    styleData = getByteFromAssets("style.data")
                    styleExtraData = getByteFromAssets("style_extra.data")
                }
            )

            // 地图加载完成监听
            setOnMapLoadedListener {
                getShopList()
            }

            // 地图状态的监听
            setCameraChangeListener { }

            // marker点击事件监听
            setOnMarkerClickListener {
                it.isInfoWindowShown
                    .conditionElse(
                        actionTrue = { it.hideInfoWindow() },
                        actionFalse = { it.showInfoWindow() }
                    )

                startDropAnimation(it)

                true
            }

            // 自定义弹框窗口
            setInfoWindowAdapter(this@OrderShipMapActivity)
            setOnInfoWindowClickListener { }

            moveCamera(CameraUpdateFactory.newLatLng(LatLng(34.7466, 113.625367))) //默认显示郑州经纬度
        }
    }

    override fun initListener() {
        // 观察已发货订单
        observe<String>("orderShipMap") {
            getViewModel()
                .delay {
                    when (it) {
                        "update" ->
                            mSendMarker?.let { marker ->
                                val typeList = marker.snippet.split(",")
                                mShipList.removeAll { it.id == typeList[1] }

                                marker.remove()
                            }

                        "refresh" -> {
                            mBinding
                                .orderMap
                                .map
                                .clear()

                            getShopList()
                        }
                    }

                }
        }
    }

    /**
     * 店铺列表
     */
    private fun getShopList() {
        getViewModel()
            .masterShop()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    mShopList.clear()
                    mShopList.contact(list)

                    // 添加店铺marker
                    mShopList.forEach {
                        mBinding
                            .orderMap
                            .map
                            .addMarker(
                                MarkerOptions()
                                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_manager22))
                                    .snippet("0,${it.id}")
                                    .position(
                                        LatLng(
                                            it.lat.doubleValue,
                                            it.lng.doubleValue
                                        )
                                    )
                            )
                    }
                },
                onFinally = { getShipList() }
            )
    }

    /**
     * 待发货订单列表
     */
    private fun getShipList() {
        getViewModel()
            .orderShipList()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    mShipList.clear()
                    mShipList.contact(list)

                    // 添加订单marker
                    mShipList.forEach {
                        (it.lat.doubleValue > 0
                                && it.lng.doubleValue > 0)
                            .condition {
                                mBinding
                                    .orderMap
                                    .map
                                    .addMarker(
                                        MarkerOptions()
                                            .icon(
                                                BitmapDescriptorFactory.fromView(
                                                    inflate<TextView>(R.layout.layout_marker)
                                                        .apply {
                                                            text = it.consignee.first().toString()
                                                        }
                                                )
                                            )
                                            .snippet("1,${it.id}")
                                            .anchor(0.5f, 0.9f)
                                            .position(
                                                LatLng(
                                                    it.lat.doubleValue,
                                                    it.lng.doubleValue
                                                )
                                            )
                                    )
                            }
                    }
                },
                onFinally = ::animateCenter
            )
    }

    /**
     * 移动镜头到当前视角
     */
    private fun animateCenter() {
        // 移动镜头到当前视角
        val bounds = LatLngBounds
            .Builder()
            .apply {
                mShopList.onEach {
                    include(
                        LatLng(
                            it.lat.doubleValue,
                            it.lng.doubleValue
                        )
                    )
                }

                mShipList.onEach {
                    (it.lat.doubleValue > 0
                            && it.lng.doubleValue > 0)
                        .condition {
                            include(
                                LatLng(
                                    it.lat.doubleValue,
                                    it.lng.doubleValue
                                )
                            )
                        }
                }
            }
            .build()

        mBinding
            .orderMap
            .map
            .animateCamera(
                CameraUpdateFactory
                    .newLatLngBounds(bounds, 150)
            )
    }

    /**
     * Marker点击跳动动画
     */
    private fun startDropAnimation(marker: Marker, duration: Long = 1500) {
        val start = SystemClock.uptimeMillis()
        val project = mBinding.orderMap.map.projection
        val markerLatLng = marker.position
        // 将地理坐标转换成屏幕坐标
        val markerPoint = project.toScreenLocation(markerLatLng)
        // 屏幕坐标上移100px
        markerPoint.offset(0, -100)
        // 将屏幕坐标转换成地理坐标
        val startLatLng = project.fromScreenLocation(markerPoint)
        // 插值器对象
        val interpolator = BounceInterpolator()

        lifecycleScope.launch(Dispatchers.IO) {
            var elapsed = SystemClock.uptimeMillis() - start
            var t = interpolator.getInterpolation(elapsed.toFloat() / duration)

            while (t < 1.0) {
                val lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude
                val lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude

                withContext(Dispatchers.Main) {
                    marker.position = LatLng(lat, lng)
                }

                delay(16)

                elapsed = SystemClock.uptimeMillis() - start
                t = interpolator.getInterpolation(elapsed.toFloat() / duration)
            }
        }
    }

    /**
     * 监听自定义infowindow窗口的infowindow事件回调
     */
    override fun getInfoWindow(marker: Marker) = kotlin.run {
        inflate<View>(R.layout.pop_ship_map).apply {
            val typeList = marker.snippet.split(",")
            when (typeList[0]) {
                "0" -> {
                    val item = mShopList.first { it.id == typeList[1] }
                    find<TextView>(R.id.pop_order_ll).isVisible = false
                    find<TextView>(R.id.pop_shop_ll).isVisible = true

                    find<TextView>(R.id.pop_shop).text = item.shopName
                }

                "1" -> {
                    val item = mShipList.first { it.id == typeList[1] }
                    find<TextView>(R.id.pop_order_ll).isVisible = true
                    find<TextView>(R.id.pop_shop_ll).isVisible = false

                    find<TextView>(R.id.pop_name).text = item.consignee
                    find<TextView>(R.id.pop_phone).text = item.phone
                    find<TextView>(R.id.pop_time1).text = item.createDate.getTimeString()
                    find<TextView>(R.id.pop_time2).text = item.estimateDate.getTimeString()

                    find<TextView>(R.id.pop_send).oneClick {
                        mSendMarker = marker

                        startActivityEx<OrderShipActivity>(
                            "orderSn" to item.sn
                        )
                    }

                    find<TextView>(R.id.pop_detail).oneClick {
                        startActivityEx<OrderDetailActivity>(
                            "orderSn" to item.sn
                        )
                    }
                }
            }
        }
    }

    /**
     * 监听自定义infowindow窗口的infocontents事件回调
     */
    override fun getInfoContents(marker: Marker) = kotlin.run {
        inflate<View>(R.layout.pop_ship_map).apply {
            val typeList = marker.snippet.split(",")
            when (typeList[0]) {
                "0" -> {
                    val item = mShopList.first { it.id == typeList[1] }
                    find<TextView>(R.id.pop_order_ll).isVisible = false
                    find<TextView>(R.id.pop_shop_ll).isVisible = true

                    find<TextView>(R.id.pop_shop).text = item.shopName
                }

                "1" -> {
                    val item = mShipList.first { it.id == typeList[1] }
                    find<TextView>(R.id.pop_order_ll).isVisible = true
                    find<TextView>(R.id.pop_shop_ll).isVisible = false

                    find<TextView>(R.id.pop_name).text = item.consignee
                    find<TextView>(R.id.pop_phone).text = item.phone
                    find<TextView>(R.id.pop_time1).text = item.createDate.getTimeString()
                    find<TextView>(R.id.pop_time2).text = item.estimateDate.getTimeString()

                    find<TextView>(R.id.pop_send).oneClick {
                        mSendMarker = marker

                        startActivityEx<OrderShipActivity>(
                            "orderSn" to item.sn
                        )
                    }

                    find<TextView>(R.id.pop_detail).oneClick {
                        startActivityEx<OrderDetailActivity>(
                            "orderSn" to item.sn
                        )
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mBinding.orderMap.onCreate(savedInstanceState)
    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        // onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mBinding.orderMap.onSaveInstanceState(outState)
    }

    override fun onResume() {
        super.onResume()
        // onResume时执行mMapView.onResume ()，重新绘制加载地图
        mBinding.orderMap.onResume()
    }

    override fun onPause() {
        super.onPause()
        // onPause时执行mMapView.onPause ()，暂停地图的绘制
        mBinding.orderMap.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        // onDestroy时执行mMapView.onDestroy()，销毁地图
        mBinding.orderMap.onDestroy()
    }

}